package com.kaoshi.controller;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.GetObjectRequest;
import com.aliyun.oss.model.OSSObject;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class OssImageUtils {
    public static byte[] getImageBytesFromOss(String bucketName, String objectKey) {
        // 创建OSSClient实例
        OSS ossClient = new OSSClientBuilder().build("oss-cn-beijing.aliyuncs.com", "LTAI5tBt44qJZWYk9LzKHcN8", "pqb08flKaUVGl7vAvuEenh3pTgZSXX");

//        endpoint: oss-cn-beijing.aliyuncs.com
//        keyId: LTAI5t8zWhY5e6SN9hJJ1Bs3
//        keySecret: GT5R9hO1gskiyzXnMamz0oUCzS1LcM
//        bucketName: spyx-h2310a
        try {
            OSSObject ossObject = ossClient.getObject(new GetObjectRequest(bucketName, objectKey));
            InputStream inputStream = ossObject.getObjectContent();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer))!= -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            // 现在outputStream中就包含了从OSS对象读取的字节数据
            return outputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭OSSClient
            ossClient.shutdown();
        }

        return null;
    }
}
